var jwt = require('jsonwebtoken') //加密
var secret = '啊哈哈哈哈哈哈哈'

//token加密
var createToken = function (data) {
    return jwt.sign(data,secret,{expiresIn:'2h'})
}

//token解密
var decodeToken = function (token) {
    return new Promise(function (resolve,reject) {
        jwt.verify(token, secret, (err, data) => {
            if (err) {
                reject(err)
            } else {
                resolve(data)
            }
        })
    })
}



exports.createToken = createToken;
exports.decodeToken = decodeToken;


// 校验token

exports.checkToken = function (req, res, callBack) {
    var token = req.headers._token;

    if (token) {
        decodeToken(token)
            .then(data => {
            callBack(data)
            })
            .catch(err => {
            console.log(err);
                res.json({
                    code: '3000',
                    msg: 'token无效或者已经过期，请登录',
                    type: 0,
                    err
            })
        })
    } else {
        res.json({
            code: '3000',
            msg: 'token不存在，请登录',
            type:0
        })
    }
}